﻿var msacademic = {

    hideToastNotification: function () {
       $('.toastRoot').slideUp();
    },

    displayToastNotification: function (title, content, timeToLive) {
        var msacademic      = $('.msacademic .content'),
            toastTemplate   = $('.toastRoot'),
            toastTitle      = toastTemplate.find('.title'),
            toastContent    = toastTemplate.find('.content');

        toastTitle.text(title);
        toastContent.text(content);
        toastTemplate.slideDown().on('click', function () {
            $(this).slideUp();
        });

        setTimeout(function () {
            toastTemplate.slideUp();
        }, (timeToLive || 10000));

    },

    dialogPopup: function (url, modal) {
        var popupRoot = $('.popupRoot'),
            modalSettings = {
                opacity:            90,
                close:              true,
                overlayClose:       true,
                onOpen:             function (dialog) {
                                        dialog.overlay.fadeIn('fast', function () {
                                            dialog.container.slideDown('fast', function () {
                                                dialog.data.fadeIn('fast');
                                            });
                                        });
                                    }
            };

        $.extend(modalSettings, modal);

        popupRoot.load(url, function () { 
            msacademic.wireActionEvents(popupRoot);
            popupRoot.modal(modalSettings); 
        });
    },

    initializeJCrop: function (maxImageHeight, maxImageWidth, hiddenCropUrlInput, settings) {
        var aspectRatio = maxImageWidth / maxImageHeight,
            target = $('.image-cropper .image'),
            
            cropUrl = target.attr('src'),
            updateCropUrl = function (coords) {

                if (parseInt(coords.w) <= 0 || parseInt(coords.h) <= 0) 
                    return;

                  var url = cropUrl + '?crop=(' + coords.x + ',' + coords.y + ',' + coords.x2 + ',' + coords.y2 + 
                           ')&cropxunits=' + target.width() + '&cropyunits=' + target.height() + 
                           '&maxwidth=' + maxImageWidth + '&maxheight=' + maxImageHeight ;

                hiddenCropUrlInput.val(url);
            },

            jCropSettings = {
                onChange:       updateCropUrl,
                onSelect:       updateCropUrl,
                bgColor:        'black',
                bgOpacity:      0.6,   
                aspectRatio:    aspectRatio
            };


            $.extend(jCropSettings, settings);
            target.Jcrop(jCropSettings);
    },

    jumpListFor: function (targets, listRoot) {
        var list = $('<ul></ul>').appendTo(listRoot);

        targets.each(function (i) {
            var listItem = $('<li class="anchor"></li>').appendTo(list)
            var current = $(this);
            
            /* Copy target text to listItem*/
            listItem.text(current.text());

            /* Mark (target, listItem) pairs */
            listItem.attr("jumpId",  'jmp-' + i     );
            current.attr( "jumpId",  'jmp-' + i     );

            /* Enable scrolling on click event */
            listItem.on('mouseup', function () { 
                $('html, body').animate({ scrollTop: current.offset().top - 70}, 700);
            });
        });

    },

    loading: function (state) {
    
        var loading =  $('.msacademic .loading');

        if (state === 'off') {
            loading.addClass('hidden');
        } else {
            loading.removeClass('hidden');
        }

    },

    multipleItemSelector : function (selectorRoot, currentItems, addedItemsHiddenInput) {
        
        var multiSelector   =   selectorRoot,
            items           =   multiSelector.find('.item'),
            itemCsv         =   "",
            getItemsCsv     =   function () { 
                                    itemCsv = "";

                                    items.each(function () {
                                       if( $(this).hasClass('bound') ) {
                                          itemCsv += $(this).data('id') + ';';
                                       }
                                    });

                                    return itemCsv.substring(0, itemCsv.length - 1);;
                                };

        // Mark currently selected items on load
        items.each(function () {
            if( currentItems[ $(this).data('id') ] !== undefined ) {
                $(this).addClass('bound');
            }
        });

        // Update hidden input on load
        addedItemsHiddenInput.val(getItemsCsv());

        // Toggle item bound state
        items.on('mouseup', function () {
            $(this).toggleClass('bound');
            addedItemsHiddenInput.val(getItemsCsv());
        });
    
    },

    transferCKTextToTextareas: function() {
        /* Transfer data from CKEDITOR instance into the textarea */

        $('.clearfix.ckeditor textarea').each(function () {
            var $textarea = $(this);
            $textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
        });
    },

    wireActionEvents: function (root) {

        $(root).on('mouseup', '.submit, .preview', function () {   
            msacademic.loading('on'); 
                
            msacademic.transferCKTextToTextareas();
            $(this).closest('form').trigger('submit');
        });
        $(root).on('mouseup', '.cancel', function () {   $.modal.close(); });
    }

}